package Andrew;

import java.io.IOException;
import java.util.HashMap;
import java.util.Vector;

import javax.jmdns.JmDNS;
import javax.jmdns.ServiceEvent;
import javax.jmdns.ServiceListener;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.SwingUtilities;

/**
 * This code was edited or generated using CloudGarden's Jigloo SWT/Swing GUI
 * Builder, which is free for non-commercial use. If Jigloo is being used
 * commercially (ie, by a corporation, company or business for any purpose
 * whatever) then you should purchase a license for each developer using Jigloo.
 * Please visit www.cloudgarden.com for details. Use of Jigloo implies
 * acceptance of these licensing terms. A COMMERCIAL LICENSE HAS NOT BEEN
 * PURCHASED FOR THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED LEGALLY FOR
 * ANY CORPORATE OR COMMERCIAL PURPOSE.
 */
public class RemoteApplet extends javax.swing.JApplet {
	// add new service type declaration here
	public static final String SERVICE_TYPE = "_media_service._tcp.local.";
	public static final String SERVICE_TYPE2 = "_screen_service._tcp.local.";
	//GUI declarations
	private JButton starterButton;
	private JScrollPane jScrollPane1;
	private JButton DeviceToggle;
	private JButton playButton;
	private JButton pauseButton;
	private JButton stopButton;
	private JButton returnButton;
	private JButton tempButton;
	private JButton listGetter;
	private JButton deviceOptionButton;
	private JButton refreshButton;
	private JButton refreshBOOM;
	private JmDNS jmdns = null;
	public String selectedDevice = "command";
	public ServiceEvent Device1 = null;
	public TCPSocketClientremote chatter;
	public Vector<JButton> listy = null;
	public Vector<JButton> DeviceButtonList = null;
	public Vector<ServiceEvent> DeviceList = new Vector<ServiceEvent>();
	public HashMap<String, ServiceEvent> mediaButtons = new HashMap<String, ServiceEvent>();
	public HashMap<String, ServiceEvent> screenButtons = new HashMap<String, ServiceEvent>();
	public ServiceEvent currentScreen = null; //information required to connect to a particular screen

	/**
	 * Auto-generated main method to display this JApplet inside a new JFrame.
	 */
	public static void main(final String[] args) {
		SwingUtilities.invokeLater(new Runnable() {
			@Override
			public void run() {
				final JFrame frame = new JFrame();
				final RemoteApplet inst = new RemoteApplet();
				frame.getContentPane().add(inst);
				((JComponent) frame.getContentPane()).setPreferredSize(inst
						.getSize());
				frame.pack();
				frame.setVisible(true);
			}
		});

	}

	public RemoteApplet() {
		super();
		initGUI();
	}

	private void initGUI() {
		try {
			this.setSize(500, 380);
			getContentPane().setLayout(null);
			{
				starterButton = new JButton();
				getContentPane().add(starterButton);
				starterButton.setText("start");
				starterButton.setBounds(12, 12, 64, 23);
				starterButton
				.addActionListener(new java.awt.event.ActionListener() {
					@Override
					public void actionPerformed(
							final java.awt.event.ActionEvent e) {
						DeviceButtonList = new Vector<JButton>();
						starterButton.setVisible(false);
						refreshButton.setVisible(true);
						try {
							jmdns = JmDNS.create();
							jmdns.addServiceListener(
									RemoteApplet.SERVICE_TYPE,
									new SampleListener());
							jmdns.addServiceListener(
									RemoteApplet.SERVICE_TYPE2,
									new SampleListener());
						} catch (final IOException e1) {
							e1.printStackTrace();
						}

					}
				});
			}
			{
				refreshButton = new JButton();
				getContentPane().add(refreshButton);
				refreshButton.setText("finish");
				refreshButton.setVisible(false);
				refreshButton.setBounds(12, 12, 75, 23);

				refreshButton
				.addActionListener(new java.awt.event.ActionListener() {
					@Override
					public void actionPerformed(
							final java.awt.event.ActionEvent e) {

						refreshButton.setVisible(false);
						deviceOptionButton.setVisible(false);
						listGetter.setVisible(false);
						clearDeviceList();
						DeviceButtonList = null;
						DeviceList = null;
						clearList();
						listy = null;
						starterButton.setVisible(true);
						jmdns.unregisterAllServices();
						jmdns.close();

					}
				});
			}

			//Makes a list of buttons form the hash table of devices.
			{
				refreshBOOM = new JButton();
				getContentPane().add(refreshBOOM);
				refreshBOOM.setVisible(true);
				refreshBOOM.setBounds(10, 40, 80, 25);
				refreshBOOM.setText("refresh");
				refreshBOOM
				.addActionListener(new java.awt.event.ActionListener() {
					@Override
					public void actionPerformed(
							final java.awt.event.ActionEvent e) {
						System.out.println(mediaButtons.toString());
						if(DeviceButtonList!=null){
							for (final JButton temp : DeviceButtonList) {
								temp.setVisible(false);
							}
						}
						
						clearList();
						final Object[] mediaKeys = mediaButtons.keySet()
						.toArray();
						final Object[] mediaValues = mediaButtons.values()
						.toArray();
						final Object[] screenKeys = screenButtons.keySet()
						.toArray();
						final Object[] screenValues = screenButtons.values()
						.toArray();
						System.out.println(mediaButtons.size());
						for (int i = 0; i < mediaButtons.size(); i++) {
							System.out.println(mediaKeys[i]);
							DeviceToggle = new JButton();
							getContentPane().add(DeviceToggle);
							DeviceToggle.setText(mediaKeys[i].toString());
							DeviceToggle.setBounds(436, 20 + i * 30, 100, 23);
							DeviceToggle.addActionListener(new java.awt.event.ActionListener() {
								@Override
								public void actionPerformed(
										final java.awt.event.ActionEvent e) {
									Device1 = mediaButtons.get(((JButton) e
											.getSource())
											.getText());
											selectedDevice = Device1
											.getName();
											// deviceOptionButton.setVisible(true);
											listGetter.setVisible(true);
								}
							});
							DeviceButtonList.add(DeviceToggle);
						}
						for (int i = 0; i < screenButtons.size(); i++) {
							System.out.println(screenKeys[i]);
							DeviceToggle = new JButton();
							getContentPane().add(DeviceToggle);
							DeviceToggle.setText(screenKeys[i].toString());
							DeviceToggle.setBounds(236, 20 + i * 30, 100, 23);
							DeviceToggle.addActionListener(new java.awt.event.ActionListener() {
								@Override
								public void actionPerformed(
										final java.awt.event.ActionEvent e) {
									currentScreen = screenButtons.get(((JButton) e.getSource()).getText());
									System.out.println("TEST: "+currentScreen.getInfo().getHostAddress());
									// deviceOptionButton.setVisible(true);
								}
							});
							DeviceButtonList.add(DeviceToggle);
						}

					}
				});

			}

			{
				deviceOptionButton = new JButton();
				getContentPane().add(deviceOptionButton);
				deviceOptionButton.setText(selectedDevice);
				deviceOptionButton.setVisible(false);
				deviceOptionButton.setBounds(155, 221, 100, 23);
				deviceOptionButton
				.addActionListener(new java.awt.event.ActionListener() {
					@Override
					public void actionPerformed(
							final java.awt.event.ActionEvent e) {
						chatter = new TCPSocketClientremote(Device1
								.getInfo().getHostAddress(), Device1
								.getInfo().getPort());
						final String msg = JOptionPane
						.showInputDialog("send console message");
						chatter.sendMessage(msg);
					}
				});
			}
			{
				listGetter = new JButton();
				getContentPane().add(listGetter);
				listGetter.setText("list");
				listGetter.setBounds(340, 221, 100, 23);
				listGetter.setVisible(false);
				listGetter
				.addActionListener(new java.awt.event.ActionListener() {
					@Override
					public void actionPerformed(
							final java.awt.event.ActionEvent e) {
						chatter = new TCPSocketClientremote(Device1
								.getInfo().getHostAddress(), Device1
								.getInfo().getPort());
						chatter.sendMessage("list");
						final Vector<String> temp = chatter.movieList;
						if (listy != null) {
							clearList();
						}
						listy = new Vector<JButton>(); // resets the
						// list for
						// updates
						for (int i = 0; i < temp.size(); i++) {
							final String tempMovieName = temp.get(i);
							tempButton = new JButton();
							getContentPane().add(tempButton);
							tempButton.setText(tempMovieName);
							tempButton.setBounds(60, 250 + 30 * i,
									tempMovieName.length() * 10, 20);
							tempButton
							.addActionListener(new java.awt.event.ActionListener() {
								@Override
								public void actionPerformed(
										final java.awt.event.ActionEvent e) {
									chatter = new TCPSocketClientremote(
											Device1.getInfo()
											.getHostAddress(),
											Device1.getInfo()
											.getPort());
									chatter.sendMessage("play->"
											+ tempMovieName);
									chatter = new TCPSocketClientremote(
											currentScreen.getInfo()
											.getHostAddress(),
											currentScreen.getInfo()
											.getPort());
									chatter.sendMessage("play->"
											+ tempMovieName);
									runCheck();
								}
							});
							listy.add(tempButton);

						}
					}
				});
			}
			{
				returnButton = new JButton();
				getContentPane().add(returnButton);
				returnButton.setText("back");
				returnButton.setBounds(76, 306, 80, 60);
				returnButton.setVisible(false);
				returnButton
				.addActionListener(new java.awt.event.ActionListener() {
					@Override
					public void actionPerformed(
							final java.awt.event.ActionEvent e) {
						chatter = new TCPSocketClientremote(Device1
								.getInfo().getHostAddress(), Device1
								.getInfo().getPort());
						chatter.sendMessage("command->back");
						chatter.play_mode = false;
						runCheck();
					}
				});
			}
			{
				stopButton = new JButton();
				getContentPane().add(stopButton);
				stopButton.setText("stop");
				stopButton.setBounds(155, 306, 80, 60);
				stopButton.setVisible(false);
				stopButton
				.addActionListener(new java.awt.event.ActionListener() {
					@Override
					public void actionPerformed(
							final java.awt.event.ActionEvent e) {
						chatter = new TCPSocketClientremote(Device1
								.getInfo().getHostAddress(), Device1
								.getInfo().getPort());
						chatter.sendMessage("command->stop");
					}
				});
			}
			{
				pauseButton = new JButton();
				getContentPane().add(pauseButton);
				pauseButton.setText("pause");
				pauseButton.setBounds(234, 306, 80, 60);
				pauseButton.setVisible(false);
				pauseButton
				.addActionListener(new java.awt.event.ActionListener() {
					@Override
					public void actionPerformed(
							final java.awt.event.ActionEvent e) {
						chatter = new TCPSocketClientremote(Device1
								.getInfo().getHostAddress(), Device1
								.getInfo().getPort());
						chatter.sendMessage("command->pause");
					}
				});
			}
			{
				playButton = new JButton();
				getContentPane().add(playButton);
				playButton.setText("play");
				playButton.setBounds(313, 306, 80, 60);
				playButton.setVisible(false);
				playButton
				.addActionListener(new java.awt.event.ActionListener() {
					@Override
					public void actionPerformed(
							final java.awt.event.ActionEvent e) {
						chatter = new TCPSocketClientremote(Device1
								.getInfo().getHostAddress(), Device1
								.getInfo().getPort());
						chatter.sendMessage("command->play");
					}
				});
			}

		} catch (final Exception e) {
			e.printStackTrace();
		}
	}

	// test method to see if the play_mode is now true
	public void runCheck() {

		for (final JButton temp : listy) {
			temp.setVisible(!chatter.play_mode);
		}
		listGetter.setVisible(!chatter.play_mode);
		returnButton.setVisible(chatter.play_mode);
		stopButton.setVisible(chatter.play_mode);
		pauseButton.setVisible(chatter.play_mode);
		playButton.setVisible(chatter.play_mode);
	}

	public void clearList() {
		if(listy!=null){
		for (final JButton temp : listy) {
			temp.setVisible(false);
		}
		}
	}

	public void clearDeviceList() {
		for (final JButton temp : DeviceButtonList) {
			temp.setVisible(false);
		}
	}

	// set of controls for the jmDNS
	class SampleListener implements ServiceListener {
		@Override
		public void serviceAdded(final ServiceEvent event) {

			final String ans = JOptionPane.showInputDialog("found device: ["
					+ event.getName() + "] \n do you want to Connect? y/n");

			if (ans.equalsIgnoreCase("y")) {
				event.getDNS().requestServiceInfo(event.getType(),
						event.getName(), 0);
			} else {
			}
			// event.getDNS().requestServiceInfo(event.getType(),
			// event.getName(), 0);
		}

		@Override
		public void serviceRemoved(final ServiceEvent event) {
			System.out.println("Service removed : " + event.getName() + "."
					+ event.getType());
			if (event.getType().equals(RemoteApplet.SERVICE_TYPE)) {
				mediaButtons.remove(event.getInfo().getName());
				System.out.println("After removal: " + mediaButtons.toString());
			}

		}

		@Override
		public void serviceResolved(final ServiceEvent event) {
			// Display some information about the service.

			System.out.println("Service resolved: " + event.getInfo().getName()
					+ ", host: " + event.getInfo().getHostAddress()
					+ ", port: " + event.getInfo().getPort());

			if (event.getType().equals(RemoteApplet.SERVICE_TYPE)) {
				System.out.println("This is a media server get its list");
				DeviceList.addElement(event);
				final ServiceEvent temp = DeviceList.lastElement();
				System.out.println("Before adding: " + mediaButtons.toString());
				mediaButtons.put(event.getInfo().getName(), temp);
				System.out.println("After adding: " + mediaButtons.toString());

			}
			//TODO as above
			if (event.getType().equals(RemoteApplet.SERVICE_TYPE2)) {
				System.out.println("This is a media server get its list");
				DeviceList.addElement(event);
				final ServiceEvent temp = DeviceList.lastElement();
				System.out.println("Before adding: " + screenButtons.toString());
				screenButtons.put(event.getInfo().getName(), temp);
				System.out.println("After adding: " + screenButtons.toString());
				/*System.out.println("This is a screen server add a button");
				DeviceList.addElement(event);
				final ServiceEvent temp = DeviceList.lastElement();
				DeviceToggle = new JButton();
				getContentPane().add(DeviceToggle);
				DeviceToggle.setText(event.getName());
				DeviceToggle.setBounds(436, 20 + DeviceList.size() * 30, event
						.getName().length() * 10, 23);
				DeviceToggle
				.addActionListener(new java.awt.event.ActionListener() {
					@Override
					public void actionPerformed(
							final java.awt.event.ActionEvent e) {
						Device1 = temp;
						selectedDevice = Device1.getName();
						// deviceOptionButton.setVisible(true);
						// listGetter.setVisible(true);
					}
				});

				DeviceButtonList.add(DeviceToggle);*/
			}
			
		}
	}

}
